<?php
/*
 * Available attribute: hide show forbid
 * 
 * forbid > show > hide
 *
 * supports:
 * *: any user
 * ?: guest users
 * @: authenticated users
 * 
 * Example:
 * 
 * Register: 'hide'=>'@'
 * 
 * Logout: 'show'=>'@'
 * 
 * Admin panel: 'hide'=>'*', 'show'=>'admin' 
 *
 */
class EPMenuRoleProcessor extends EPMenuProcessor{

	private $_roleCache=array();

	public function afterParse($menuList){


	}

	public function beforeRender($menuList){
		$this->processListRecursive($menuList);
	}

	public function afterRender($menuList){

	}

	private function processListRecursive($menuList){
		$menuItems=$menuList->getMenuItems();
		foreach($menuItems as $menuItem){
			$hide=$menuItem->getAttribute('hide');
			if($hide!==NULL){
				if($this->hasRole($hide)){
					$menuItem->visible=false;
				}
			}
				
			$show=$menuItem->getAttribute('show');
			if($show!==NULL){
				if($this->hasRole($show)){
					$menuItem->visible=true;
				}else{
					$menuItem->visible=false;
				}
			}
				
			$forbid=$menuItem->getAttribute('forbid');
			if($forbid!==NULL){
				if($this->hasRole($forbid)){
					$menuItem->visible=false;
				}
			}

			if($menuItem->hasSubMenu()){
				$submenu=$menuItem->getSubMenu();
				$this->processListRecursive($submenu);
			}
		}
	}

	private function hasRole($role){
		$user=Yii::app()->user;

		if($role==='*')
		return true;
		else if($role==='?' && $user->getIsGuest())
		return true;
		else if($role==='@' && !$user->getIsGuest())
		return true;


		if(!isset($this->_roleCache[$role])){
			$this->_roleCache[$role]=$user->checkAccess($role,Yii::app()->user->getId());
		}

		return $this->_roleCache[$role];
	}

}